package com.hetao.xx.orm;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.hetao.xx.game.model.Goods;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.HashMap;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    private final String TAG = getClass().getSimpleName();
    private final static String DATABASE="htjh.db";
    private final static int VERSION=5;
    public DatabaseHelper(Context context) {
        super(context, DATABASE, null, VERSION);
    }
    private static DatabaseHelper instance;
    public static synchronized DatabaseHelper getInstance(Context context){

        if(instance==null){
            synchronized (DatabaseHelper.class){
                if(instance==null){
                    instance=new DatabaseHelper(context);
                }
            }
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        Log.i(TAG, "onCreate");
        try {
            TableUtils.createTable(connectionSource, UserVo.class);
            TableUtils.createTable(connectionSource, GoodsVo.class);
            TableUtils.createTable(connectionSource, UserGoodsVo.class);
            TableUtils.createTable(connectionSource, NpcVo.class);
            TableUtils.createTable(connectionSource, PlaceVo.class);
            TableUtils.createTable(connectionSource, PlaceNpcVo.class);
            TableUtils.createTable(connectionSource, NpcEventVo.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        //1如果数据库升级，要先删除之前的表
        Log.i(TAG, "onUpgrade  oldVersion:"+i+"   newVersion"+i1);
        try {
            //参数1：连接资源，参数2：实体类 参数3：忽略错误
            TableUtils.dropTable(connectionSource, UserVo.class, true);
            TableUtils.dropTable(connectionSource, GoodsVo.class, true);
            TableUtils.dropTable(connectionSource, UserGoodsVo.class, true);
            TableUtils.dropTable(connectionSource, NpcVo.class, true);
            TableUtils.dropTable(connectionSource, PlaceVo.class, true);
            TableUtils.dropTable(connectionSource, PlaceNpcVo.class, true);
            TableUtils.dropTable(connectionSource, NpcEventVo.class, true);
            onCreate(sqLiteDatabase, connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
